package com.yangrui.app.controller;

import com.yangrui.app.entity.User;
import com.yangrui.app.group.InsertGroup;
import com.yangrui.app.interceptor.Token;
import com.yangrui.app.service.UserService;
import com.yangrui.app.util.Result;
import com.yangrui.app.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.bind.BindResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/v1/user")
@Api(value = "用户接口", tags = "用户接口")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 当实体参数未通过HibernateValidated校验时，记录日志并抛出运行时异常
     *
     * @param bindingResult 校验错误实例
     */
    private void throwValidationException(BindingResult bindingResult) {
        for (FieldError error : bindingResult.getFieldErrors()) {
            String errorMsg = String.format("%s 参数的 %s 属性爆发错误：%s",
                    error.getObjectName(),
                    error.getField(),
                    error.getDefaultMessage());
            log.info(errorMsg);
            // 手动抛出异常，被全局异常处理捕获
            throw new RuntimeException(errorMsg);
        }
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "用户注册")
    public Result register(@Validated(InsertGroup.class) @RequestBody User user,
                           BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throwValidationException(bindingResult);
        }

        return userService.register(user) >0 ? Result.ok() : Result.fail();
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public Result login(@ApiParam(value = "账号" ,required = true ,example = "admin")
                            @RequestParam String username,
                        @ApiParam(value = "密码" ,required = true ,example = "123456")
                            @RequestParam String password) {
        User user = userService.login(username, password);
        if(user.getId()== -1){
            return Result.fail(0,"账号不存在");
        }
        if(user.getId()== -2){
            return Result.fail(0,"密码错误");
        }
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", user.getId());
        userMap.put("username", user.getUsername());
        userMap.put("avatar", user.getAvatar());
        userMap.put("token", TokenUtil.build(user));
        return Result.ok(userMap);
    }

    @Token
    @GetMapping("/select-by-id")
    @ApiOperation(value = "根据id查询用户", notes = "根据id查询用户")
    public Result selectById(@ApiParam(value = "用户id" ,required = true ,example = "1")
                             @RequestParam Integer id) {
        return Result.ok(userService.selectById(id));
    }
}
